package config

import (
	"github.com/cz-it/golangutils/log"

	"errors"
	"encoding/xml"
	"os"
	"strings"
	"strconv"
	"net"
	"fmt"
)



type ConfigInfo struct {
	XMLName xml.Name `xml:"config"`
	IP      string   `xml:"ip"`
	Port    int   `xml:"port"`

	// log config
	LogPath string   `xml:"log_path"`
	LogName string   `xml:"log_name"`
	LogBaseName string `xml:"log_base_name"`

	// daemon info
	LockFile string  `xml:"lockfile"`
	PidFile  string  `xml:"pidfile"`

	// other info
	Host    net.IP

}

var LogPath string
var LogName string
var LogBaseName string
var LockFile string
var PidFile  string
var Host    net.IP
var Port    int 
var LogLvl  log.Level
var IP      string


func Load(filePath string)(error){

	var config  ConfigInfo

	fd,err := os.Open(filePath)
	defer fd.Close()
	if err != nil {
		return err
	}

	finfo, err := fd.Stat()
	if err!= nil {
		return err
	}

	len := finfo.Size()
	
	buf := make ([]byte,len) // Dose some method can release the make byte?

	rst ,err := fd.Read(buf)
	if err != nil || rst != int(len){
		return errors.New("Read config error")
	}
	
	err = xml.Unmarshal(buf,&config)
	if err != nil {
		return err
	}

	convertIP(&config)
	// TODO: add value checking

	LogPath = config.LogPath
	LogName = config.LogName
	LogBaseName = config.LogBaseName

	LockFile = config.LockFile
	PidFile  = config.PidFile

	Host   = config.Host
	Port   = config.Port
	IP     = config.IP
	LogLvl = log.DEBUG

	fmt.Printf("Load config file %s success \n",filePath)
	
	return nil
}

func convertIP(cfg *ConfigInfo){
	// TODO: add value checking
	ips   := strings.Split(cfg.IP,".")
	ip1,_ := strconv.Atoi(ips[0])
	ip2,_ := strconv.Atoi(ips[1])
	ip3,_ := strconv.Atoi(ips[2])
	ip4,_ := strconv.Atoi(ips[3])

	cfg.Host =  net.IP{byte(ip1),byte(ip2),byte(ip3),byte(ip4)}
}



















